<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <!-- 栅格布局 搜索新增开始 -->
        <div class="app-containers">
          <el-row :gutter="20">
            <el-col :span="5">
              <div class="grid-content bg-purple">
                <el-input
                  v-model="directoryName"
                  placeholder="请输入目录名称"
                />
                <el-select v-model="value" placeholder="请选择状态">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </el-col>
            <el-col :span="16">
              <div class="grid-content bg-purple">
                <el-button @click="clearFn()">清除</el-button>
                <el-button type="primary" @click="searchFn()">搜索</el-button>
              </div>
            </el-col>
            <el-col :span="1">
              <div class="grid-content bg-purple">
                <el-button type="success" @click="addFn()">新增目录</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- 栅格布局 搜索新增结束 -->
        <el-alert
          :title="`数据一共${counts}条`"
          type="info"
          show-icon
          :closable="false"
        />
        <!-- 渲染数据 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column
            label="序号"
            type="index"
            :index="indexMethod"
            sortable=""
          />
          <el-table-column prop="subjectName" label="所属学科" width="80px" />
          <el-table-column
            prop="directoryName"
            label="目录名称"
            width="100px"
          />
          <el-table-column prop="username" label="创建者" width="100px" />
          <el-table-column prop="addDate" label="创建日期">
            <template #default="{ row }">
              {{ row.addDate | formatTime('YYYY-MM-DD HH:MM:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="totals" label="面试题数量" width="120px" />
          <el-table-column
            prop="state"
            label="状态"
            width="120px"
            :formatter="formOfEmploymentEmploymentFn"
          />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                v-if="row.state === 1"
                type="text"
                size="small"
                @click="stateFN(row)"
              >
                启用
              </el-button>
              <el-button v-else type="text" size="small" @click="stateFN(row)">
                禁用
              </el-button>
              <el-button type="text" size="small" @click="editFn(row.id)">
                修改
              </el-button>
              <el-button type="text" size="small" @click="delFn(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件开始 -->
        <el-row>
          <el-col :span="12"><div class="grid-content bg-purple" /></el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light">
              <div class="fycs">
                <el-pagination
                  :current-page="currentPage4"
                  :page-sizes="[5, 10, 15, 20]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="counts"
                  :page-count="counts * 0"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 分页组件结束 -->
      </el-card>
      <!-- 新增编辑的弹层 -->
      <el-dialog
        :visible="showDialog"
        :title="showDialogTitle"
        @close="closeFn()"
      >
        <!-- 表单内容 -->
        <el-form
          ref="ruleForm"
          label-width="100px"
          :model="formData"
          :rules="rules"
        >
          <el-form-item label="所属学科" prop="subjectID">
            <el-select v-model="formData.subjectID" placeholder="请选择">
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称" prop="directoryName">
            <el-input v-model="formData.directoryName" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="text-align: right">
            <el-button @click="closeFn()">取消</el-button>
            <el-button type="primary" @click="submitsubject()">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getDirectoryslistApi,
  getSearchdApi,
  getDeldirectoryApi,
  getsubjectsApi,
  getAddirectoryApi,
  getEditirectoryApi,
  getDeldirectorysApi,
  getdirectorystateApi,
  getSearchdsApi
} from '@/api/directorys'
import { status } from '@/api/constants/constants'
export default {
  data() {
    return {
      subjectList: {}, // 获取简单学科列表
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        directoryName: [
          { required: true, message: '请选择目录名称', trigger: 'blur' }
        ]
      },
      value: '',
      options: [
        {
          value: '1',
          label: '启用'
        },
        {
          value: '2',
          label: '关闭'
        }
      ],
      formData: {
        subjectID: '', // 所属学科ID
        directoryName: '' // 目录名称
      },
      showDialog: false, // 弹层
      loading: false,
      counts: 0,
      page: 1,
      pagesize: 10,
      directoryName: '', // 目录名称
      currentPage4: 1, // 分页组件
      tableData: [], // 表格假数据
      id: this.$route.query.id // 根据id判断是不是传输过来的
    }
  },
  computed: {
    // 通过计算属性来计算 是编辑还是添加 的标题 通过id来判断
    showDialogTitle() {
      return this.formData.id ? '编辑目录' : '新增目录'
    }
  },
  created() {
    this.getdirectoryslist() // 获取当前页数据
  },
  methods: {
    async tzlist() {
      this.loading = true // 设置加载等待动画
      const res = await getSearchdsApi(this.id)

      // const res = await getDirectoryslistApi(this.page, this.pagesize)
      this.counts = res.counts
      this.tableData = res.items
      this.loading = false
    },
    // clearF 清除
    clearFn() {
      this.subjectName = ''
    },
    // 搜索
    async searchFn() {
      this.loading = true // 设置加载等待动画
      const data = await getSearchdApi(this.directoryName, this.state)
      this.tableData = data.items
      this.counts = data.counts
      if (this.counts === 0) {
        this.$message.error('没有当前目录')
      }
      this.loading = false
    },
    // 获取当前页数据
    async getdirectoryslist() {
      if (this.id) {
        this.tzlist()
      } else {
        this.loading = true // 设置加载等待动画
        const res = await getDirectoryslistApi(this.page, this.pagesize)
        this.counts = res.counts
        this.tableData = res.items
        this.loading = false
      }
    },
    // 页码数据改变时
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getdirectoryslist() // 数据发生改变重新渲染数据
    },
    // 页面变动的数据
    handleCurrentChange(val) {
      this.page = val
      this.getdirectoryslist() // 数据发生改变重新渲染数据
    },
    // 处理序号问题 根据index的变化 进
    indexMethod(index) {
      // 当前返回的序号 前面有多少条数据
      // 前面一共有多少条数据 前面的多少页 * 每页的数据的条数 + index +1
      return (this.page - 1) * this.pagesize + index + 1
    }, // 删除数据
    delFn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await getDeldirectoryApi(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getdirectoryslist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }, // 关闭弹层
    closeFn() {
      this.showDialog = false
      this.formData = {} // 提交完了重置一下表单
      this.$refs.ruleForm.resetFields() // 清空表单验证
    },
    // 用做数据回显吧
    async subjectLists() {
      const data = await getsubjectsApi()
      this.subjectList = data
    },
    // 修改学科打开窗口
    async editFn(id) {
      const data = await getDeldirectorysApi(id) // 获取数据回显
      this.subjectLists()
      //   this.subjectList.subjectName 他默认选中的名字根据 现在的ID subjectID 来遍历？
      this.formData = data
      this.showDialog = true

      console.log(id)
    }, // 新增学科打开窗口
    addFn() {
      this.subjectLists()
      this.showDialog = true
    },
    // 新增学科请求接口
    async submitsubject(id) {
      this.$refs.ruleForm.validate(async (vaild) => {
        if (vaild) {
          if (!this.formData.id) {
            await getAddirectoryApi(
              this.formData.subjectID,
              this.formData.directoryName
            )
            this.$message.success('添加成功')
          } else {
            this.showDialog = false
            console.log(this.formData)
            await getEditirectoryApi(this.formData)
            this.$message.success('编辑成功')
          }
        } else {
          this.$message.error('表单内容不满足，请重新填写 ')
        }
      })

      this.getdirectoryslist() // 提交完了重新请求数据
      this.showDialog = false
    }, // 设置启用关闭状态
    async stateFN(row) {
      if (row.state === 1) {
        row.state = 0
      } else {
        row.state = 1
      }
      await getdirectorystateApi(row)
        .then(() => {
          this.$message.success('更改状态成功')
        })
        .catch((error) => {
          this.$message.error(error)
        })
    }, // 判断是否启用
    formOfEmploymentEmploymentFn(row, column, cellValue, index) {
      // 常量抽离，将用于判断的表示 抽离到常量模块  常量就是可以遍历 可以枚举的数据
      // find 查到到符合的元素并且返回
      const result = status.find((item) => item.value === +cellValue)
      return result ? result.label : '未知'
    } //
  }
}
</script>
<style lang="scss" scoped>
.app-containers {
  margin-bottom: 15px;
}
::v-deep .el-table thead {
  color: #909399;
  font-weight: 500;
  background-color: #909399;
}
.fycs {
  margin-top: 15px;
}
::v-deep.el-dialog__header {
  background: -webkit-gradient(
    linear,
    left top,
    right top,
    from(#1493fa),
    to(#01c6fa)
  );
  background: linear-gradient(90deg, #1493fa, #01c6fa);
  background: #409eff;
  border-radius: 9px 9px 0 0;
}
</style>
